//
//  HMComposeView.swift
//  WeiBo
//
//  Created by Feng on 2017/6/11.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit
import pop
import YYModel

class HMComposeView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: --懒加载控件
    //罩层图片
    private lazy var blurImageView: UIImageView =
    {
        let image = self.getScreenshot().applyLightEffect()
        let imageView = UIImageView(image: image)
        
        return imageView
    }()
    
    //按钮数组
    private lazy var composeButtonArray: [HMComposeButton] = [HMComposeButton]()
    
    //菜单模型数组
    private lazy var composeModelArray: [HMCompose] =
    {
        let array = self.loadComposeButtonData()
        
        return array
    }()
    
    //目标控制器
    var target: UIViewController?

    //MARK: --显示罩层视图
    func show(targetVC: UIViewController)
    {
        self.target = targetVC
        
//        let window = UIApplication.shared.keyWindow
//        
//        window?.addSubview(self)
        
        //  如果添加到window上会挡住视图控制器
        self.target?.view.addSubview(self)
        
        startPopAnimation(isUp: true)
    }
    
    //MARK: --屏幕截图
    private func getScreenshot() -> UIImage
    {
        //开启图片上下文
        let window = UIApplication.shared.keyWindow!
        UIGraphicsBeginImageContext(window.size)
        
        //设置图片截取范围
        //afterScreenUpdates 表示是否等到屏幕更新后才截取
        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.size), afterScreenUpdates: false)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭图片上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    //MARK: --设置界面
    private func setupUI()
    {
        backgroundColor = RandomColor()
//        self.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        
        addSubview(blurImageView)
        //此方法放在下面,因为这时候才确定了self.size
        addChildButton()
//        startPopAnimation(isUp: true)
    }
    
    //MARK: --添加按钮
    private func addChildButton()
    {
        //按钮的大小
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 110
        
        let buttonMargin: CGFloat = (self.width - 3 * buttonWidth) / 4
        
        print(self.width)
        
        for i in 0..<composeModelArray.count {
            let button = HMComposeButton()
            //列索引
            let columnIndex = i % 3
            //行索引
            let rowIndex = i / 3
            //x坐标
            let x = buttonMargin * CGFloat(columnIndex + 1) + buttonWidth * CGFloat(columnIndex)
            let y = buttonMargin * CGFloat(rowIndex) + buttonHeight * CGFloat(rowIndex) + ScreenHeight
            
            button.frame = CGRect(x: x, y: y, width: buttonWidth, height: buttonHeight)
//            button.setImage(UIImage(named:"tabbar_compose_idea"), for: .normal)
//            button.setTitle("文字", for: .normal)
            button.setImage(UIImage(named:composeModelArray[i].icon!), for: .normal)
            button.setTitle(composeModelArray[i].title, for: .normal)
            button.setTitleColor(UIColor.darkGray, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.tag = i
            
            //注册点击事件
            button.addTarget(self, action: #selector(composeButtonAction(btn:)), for: .touchUpInside)
            
            addSubview(button)
            //添加到数组
            composeButtonArray.append(button)
        }
    }
    
    //MARK: --按钮点击事件
    @objc private func composeButtonAction(btn: HMComposeButton)
    {
        UIView.animate(withDuration: 0.25, animations: { 
            
            for button in self.composeButtonArray
            {
                button.alpha = 0.3
                
                if button == btn
                {
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                }
                else
                {
                    button.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
                }
            }
        }) { (_) in
            
            UIView.animate(withDuration: 0.25, animations: { 
                
                for button in self.composeButtonArray
                {
                    button.alpha = 1
                    button.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                
                //回调
                
                /*
                 字符串转成实例对象
                 1. 自定义的类名需要加上命名空间
                 2. 类型需要转成成指定类型
                 3. 使用类型创建实例的时候，不能使用‘()’, 需要使用‘类型.init()’
                 */
                
                //  1.通过字符串获取对应的类型
                let model = self.composeModelArray[btn.tag]
                let classType = NSClassFromString(model.className!) as! UIViewController.Type
                //  2.根据类型创建实例
                let vc = classType.init()
                //添加导航控制器
                let nav = HMCustomNavigationController(rootViewController: vc)
                
                self.target?.present(nav, animated: true, completion: {
                    self.removeFromSuperview()
                })
            })
        }
    }
    
    //MARK: --开启pop动画
    private func startPopAnimation(isUp: Bool)
    {
        if !isUp
        {
            //向下pop动画
            composeButtonArray = composeButtonArray.reversed()
        }
        
        for (i,button) in composeButtonArray.enumerated()
        {
            //创建弹簧动画对象
            let popSpringAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //  动画执行目的地
            if isUp
            {
                popSpringAnimation?.toValue = CGPoint(x: button.center.x, y: button.center.y - 350)
            }
            else
            {
                popSpringAnimation?.toValue = CGPoint(x: button.center.x, y: button.center.y + 350)
            }
            //  设置幅度
            popSpringAnimation?.springBounciness = 10
            //  设置弹簧初始化速度
            popSpringAnimation?.springSpeed = 10
            //  设置动画间隔时间
            popSpringAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            
            //  执行pop动画
            button.pop_add(popSpringAnimation, forKey: nil)
        }
    }
    
    //MARK: --点击屏幕
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        startPopAnimation(isUp: false)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            self.removeFromSuperview()
        }
    }
    
    //MARK: --加载按钮模型数据
    private func loadComposeButtonData() -> [HMCompose]
    {
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        
        let dataArray = NSArray(contentsOfFile: path) as! [[String: Any]]
        
        let modelArray = NSArray.yy_modelArray(with: HMCompose.self, json: dataArray) as! [HMCompose]
        
        return modelArray
    }
}
